package com.event.controller;

import com.event.pojo.Result;
import com.event.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.event.pojo.Result.*;

@RestController
@RequestMapping("/upload")
public class FiledUploadController {

    @PostMapping("/uploadFile")
    public Result<String> filedUpload(MultipartFile file) throws IOException {
        String url = "";
        //把文件内容存放到本地磁盘上
        String filename = file.getOriginalFilename();//获取文件名称
        String DateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String fole = "E:\\temp\\"+DateTime;
        File floderFile = new File(fole);
        if(!floderFile.exists()) {
            floderFile.mkdirs();
        }
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() +  suffix;
        String filePath = fole+"\\"+newFileName;
        try{
            //file.transferTo(new File(filePath));  文件存放在本地路径
            //文件存放在阿里云
            url = AliOssUtil.uploadFile(newFileName,file.getInputStream());
        }catch (Exception e) {
            return error("文件上传失败");
        }

        return success(url);
    }
}
